package org.dreamwork.cai.monitor.web;

import org.dreamwork.misc.MimeType;
import org.dreamwork.misc.MimeTypeManager;
import org.dreamwork.util.IOUtil;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;

@WebServlet (urlPatterns = "/favicon.ico")
public class FaviconServlet extends HttpServlet {
    @Override
    protected void doGet (HttpServletRequest request, HttpServletResponse response) throws IOException {
        ClassLoader loader = getClass ().getClassLoader ();
        try (InputStream in = loader.getResourceAsStream ("images/favicon.ico")) {
            if (in != null) {
                MimeType mime = MimeTypeManager.getMimeType ("ico");
                if (mime != null) {
                    response.setContentType (mime.getName ());
                } else {
                    response.setContentType ("image/x-icon");
                }

                response.setHeader("Cache-Control", "public");
                response.setHeader("Pragma", "Pragma");
                response.setDateHeader("Last-Modified",1);
                response.setDateHeader("Expires",Long.MAX_VALUE);

                IOUtil.dump (in, response.getOutputStream ());
            } else {
                response.sendError (HttpServletResponse.SC_NOT_FOUND);
            }
        }
    }

    @Override
    protected long getLastModified (HttpServletRequest req) {
        return 1;
    }
}
